<template>
  <div class="am-u-sm-12 am-u-md-12 am-u-lg-12">
    <div class="widget am-cf">
      <div class="widget-head am-cf">
        <div class="widget-title am-fl">{{formData.activityId ? '编辑活动' : '新建活动'}}</div>
        <div class="widget-function am-fr">
          <button
            type="button"
            class="am-btn am-btn-default"
            @click="$router.go(-1)"
          >返回</button>
        </div>
      </div>
      <div class="formEdit">
        <el-form
          :model="formData"
          ref="activityForm"
          label-width="150px"
          :rules="formRules"
        >

          <el-form-item
            label="请选择期数："
            required
          >
            <el-col :span="7">
              <el-form-item prop="areaTeamId">
                <el-select v-model="formData.areaTeamId">
                  <el-option
                    v-for="(item, index) in areaTeams"
                    :key="index"
                    :label="item.text"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="7">
              <el-form-item prop="periodId">
                <el-select
                  v-model="formData.periodId"
                  placeholder="选择期数"
                >
                  <el-option
                    v-for="(item, index) in periods"
                    :key="index"
                    :label="item.periodName"
                    :value="item.periodId"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>

          </el-form-item>
          <el-form-item
            label="活动名称："
            prop="activityName"
          >
            <el-input
              v-model="formData.activityName"
              placeholder="请填写"
              class="inputBox"
            />
          </el-form-item>
          <el-form-item
            label="活动详情："
            prop="activityContent"
          >
            <editor v-model="formData.activityContent"></editor>
          </el-form-item>
          <el-form-item
            label="活动时间："
            prop="activityStartDate"
          >
            <el-date-picker
              class="inputBox"
              v-model="formData.activityStartDate"
              type="date"
              placeholder="选择日期"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item
            label="最大报名数："
            prop="maxRegNum"
            required
          >
            <el-input
              v-model="formData.maxRegNum"
              placeholder="请填写"
              class="inputBox"
            />
          </el-form-item>
          <el-form-item
            label="报名成功后提示语："
            prop="successMsg"
          >
            <el-input
              v-model="formData.successMsg"
              placeholder="请填写"
              class="inputBox"
            />
          </el-form-item>
          <el-form-item
            label="报名成功跳转链接："
            prop="successUrl"
          >
            <el-input
              v-model="formData.successUrl"
              placeholder="请填写"
              class="inputBox"
            />
          </el-form-item>
          <div>
            <el-row>
              <el-col
                :span="6"
                v-if="categoryList.length>0"
              >
                <el-form-item
                  label="来源大小类："
                  prop="parentFromCategoryId"
                >
                  <el-select v-model="formData.parentFromCategoryId">
                    <el-option
                      v-for="(item, index) in categoryList"
                      :label="item.parentFromCategory.categoryName"
                      :value="item.parentFromCategory.categoryId"
                      :key="item.parentFromCategory.categoryId"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="4">
                <el-form-item
                  label-width="30px"
                  prop="childFromCategoryId"
                  v-if="categoryList.length>0"
                >
                  <el-select v-model="formData.childFromCategoryId">
                    <el-option
                      v-for="(item, index) in childCategoryList"
                      v-show="item.categoryId"
                      :label="item.categoryName"
                      :value="item.categoryId"
                      :key="item.categoryId"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </div>

          <el-form-item
            label="前端展示字段："
            required
          >
            <el-checkbox
              checked
              disabled
            >学生姓名</el-checkbox>
            <el-checkbox
              checked
              disabled
            >电话号码</el-checkbox>
            <el-checkbox
              checked
              disabled
            >年级</el-checkbox>
            <div>
              <div
                class="fieldItem"
                v-for="(item, fIndex) in formData.fields"
                :key="`${item.title}-${item.type}-${item.requireStatus}`"
              >
                <span class="fieldShowTitle">{{item.title}}</span>
                <el-select
                  v-if="item.type === 1"
                  v-model="showFieldSelect"
                >
                  <el-option
                    v-for="(item, index) in item.msg"
                    :label="item"
                    :key="index"
                    :value="index"
                  ></el-option>
                </el-select>
                <el-input
                  v-if="item.type === 0"
                  :value="item.tips"
                  style="width: 200px"
                  disabled
                >
                </el-input>
                <el-radio-group
                  v-if="item.type === 2"
                  v-model="showRadio"
                >
                  <el-radio
                    v-for="(item, index) in item.msg"
                    :key="index"
                    :label="index"
                  >
                    {{item}}
                  </el-radio>
                </el-radio-group>
                <el-checkbox-group
                  v-if="item.type === 3"
                  v-model="showCheckList"
                >
                  <el-checkbox
                    v-for="(item, index) in item.msg"
                    :key="index"
                    :label="item"
                  >
                  </el-checkbox>
                </el-checkbox-group>
                <span
                  v-if="!unDeleteShow"
                  @click="deleteShowField(fIndex)"
                  class="deleteShowField"
                ><i
                    class="el-icon-minus"
                    style="cursor: pointer;"
                  ></i></span>
              </div>
            </div>
            <div
              v-if="!unDeleteShow"
              class="addField"
              @click="addField"
            >
              <el-button type="primary">添加展示字段</el-button>
            </div>
          </el-form-item>
          <el-form-item
            label="上传banner图："
            required
            prop="bannerUrl"
          >
            <file-upload
              extensions="jpg,png"
              @uploaded="handleUpload"
            >
              <div>建议上传750x750 banner图</div>
              <img
                v-if="formData.bannerUrl"
                class="am-margin-top am-radius"
                :src="formData.bannerUrl"
                style="width:168px;height:168px"
              >
            </file-upload>
          </el-form-item>
          <el-form-item
            label="上架状态："
            prop="shelvesStatus"
          >
            <el-select v-model="formData.shelvesStatus">
              <el-option
                value="1"
                label="是"
              ></el-option>
              <el-option
                value="0"
                label="否"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div class="saveFooter">
          <el-button @click="saveForm">保存</el-button>
        </div>
      </div>
    </div>
    <window
      ref="win"
      title="添加展示字段"
    >
      <div class="schoolTeam">
        <div>
          <el-row
            :gutter="10"
            justify="center"
          >
            <el-col :span="6">类型：</el-col>
            <el-col :span="12">
              <el-radio-group
                v-model="fieldRadio"
                name='radio'
              >
                <el-radio :label="0">单行文本框</el-radio>
                <el-radio :label="1">下拉框</el-radio>
                <el-radio :label="2">单选</el-radio>
                <el-radio :label="3">多选</el-radio>
              </el-radio-group>
              <div>
                <div v-if="fieldRadio === 0">
                  <el-input
                    v-model="fieldTitle"
                    placeholder="字段标题"
                    class="fieldInput"
                  ></el-input>
                  <el-input
                    v-model="fieldTips"
                    placeholder="提示语"
                    class="fieldInput2"
                  ></el-input>
                </div>
                <div v-if="fieldRadio !== 0">
                  <el-input
                    v-model="fieldTitle"
                    placeholder="字段标题"
                    class="fieldInput"
                  ></el-input>
                  <div class="fieldRight">
                    <div
                      v-for="(item, index) in fieldOption"
                      :key="`${item}`"
                      class="fieldRightItem"
                    >
                      <el-input
                        placeholder="选项"
                        class="fieldInput2"
                        v-model="fieldValue[index]"
                      ></el-input>
                      <span @click="addorDelFieldOption(index)"><i :class="index ===0 ?'el-icon-plus' : 'el-icon-minus'"></i></span>
                    </div>

                  </div>

                </div>
              </div>
            </el-col>
          </el-row>
          <el-row
            :gutter="10"
            justify="start"
            class="neccessRow"
          >
            <el-col :span="8">
              <el-radio-group v-model="isNeccess">
                <el-radio :label="1">必填</el-radio>
                <el-radio :label="0">非必填</el-radio>
              </el-radio-group>
            </el-col>
          </el-row>
        </div>
        <div>
          <el-row justify="center">
            <el-col :span="24">
              <el-button @click="saveFieldRadio">保存</el-button>
            </el-col>
          </el-row>
        </div>
      </div>
    </window>
  </div>
</template>

<script>
import io from '../../lib/io'
import util from '../../lib/util'
import { regLevels } from '../../lib/global'
import moment from 'moment'

export default {
  data() {
    let validateMaxRegNum = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入最大报名数'))
      } else if (!/^[0-9]*$/.test(value)) {
        callback(new Error('请输入数字'))
      } else {
        callback()
      }
    }
    return {
      formData: {
        areaTeamId: '',
        activityContent: '',
        activityStartDate: '',
        activityName: '',
        bannerUrl: '',
        fields: [],
        maxRegNum: '',
        successMsg: '',
        periodId: '',
        shelvesStatus: '',
        activityId: '',
        parentFromCategoryId: '',
        childFromCategoryId: ''
      },
      categoryList: [],
      childCategoryList: [],
      fieldValue: [],
      fieldOption: [1],
      fieldRadio: 0,
      isNeccess: 1,
      courseTemplateData: {},
      campuses: [],
      editable: true,
      periods: [],
      segments: [],
      fieldTitle: '',
      fieldTips: '',
      showFieldSelect: [],
      showCheckList: [],
      showRadio: 0,
      unDeleteShow: false,
      formRules: {
        areaTeamId: [
          { required: true, message: '请选择地区', trigger: 'change' }
        ],
        periodId: [
          { required: true, message: '请选择期数', trigger: 'change' }
        ],
        activityName: [
          {
            required: true,
            message: '请填写活动名称',
            trigger: 'blur'
          }
        ],
        activityContent: [
          {
            required: true,
            message: '请填写活动详情',
            trigger: 'blur'
          }
        ],
        activityStartDate: [
          {
            required: true,
            type: 'date',
            message: '请选择时间',
            trigger: 'blur'
          }
        ],
        maxRegNum: [{ validator: validateMaxRegNum, trigger: 'blur' }],
        successMsg: [
          { required: true, message: '请填写报名成功后提示语', trigger: 'blur' }
        ],
        successUrl: [
          {
            required: true,
            message: '请填写报名成功跳转链接',
            trigger: 'blur'
          }
        ],
        shelvesStatus: [
          { required: true, message: '请选择上下架状态', trigger: 'change' }
        ],
        parentFromCategoryId: [
          { required: true, message: '请选择大类', trigger: 'change' }
        ],
        childFromCategoryId: [
          { required: true, message: '请选择小类', trigger: 'change' }
        ],
        bannerUrl: [{ required: true, message: '请上传图片', trigger: 'blur' }]
      }
    }
  },
  components: {},
  watch: {
    fieldRadio: function(newValue, old) {
      this.fieldOption = [1]
      this.fieldValue = []
      this.fieldTitle = ''
      this.fieldTips = ''
    },
    'formData.areaTeamId': function(val, oldVal) {
      if (oldVal) {
        this.formData.periodId = ''
      }
      this.loadPeriodData()
      this.getSource()
    },
    'formData.parentFromCategoryId': function(val, oldVal) {
      if (val) {
        this.updateChildCategory(val)
      }
      if (oldVal) {
        this.formData.childFromCategoryId = ''
      }
    }
  },
  created() {
    let { id } = this.$route.params
    this.formData.activityId = id
    if (this.formData.activityId) {
      this.unDeleteShow = true
      io.post(
        io.findOneActivityDetail,
        { activityId: this.formData.activityId },
        ret => {
          if (ret.success) {
            this.formData = ret.data
            this.formData.fields = JSON.parse(ret.data.showFields)
            delete this.formData.showFields
            this.formData.activityStartDate = new Date(
              Number(this.formData.activityStartDate)
            )
            this.getSource().then(() => {
              if (this.formData.parentFromCategoryId) {
                this.updateChildCategory(this.formData.parentFromCategoryId)
              }
            })
          } else {
            this.$alert(ret.desc)
          }
        }
      )
    }
  },
  computed: {
    areaTeams: function() {
      var options = (this.$root.config.areaTeams || []).map(function(item) {
        return { value: item.areaTeamId, text: item.name }
      })
      return options
    }
  },
  mounted() {},
  methods: {
    updateChildCategory(val) {
      let currentArr = []
      this.categoryList.map(item => {
        if (item.parentFromCategory.categoryId === val) {
          if (item.childFromCategories.length > 0) {
            currentArr = item.childFromCategories
          }
        }
      })
      this.childCategoryList = currentArr
    },
    deleteShowField(index) {
      this.formData.fields.splice(index, 1)
      this.$forceUpdate()
    },
    saveForm() {
      this.$refs.activityForm.validate(valid => {
        if (valid) {
          let sumbitData = {
            ...this.formData
          }
          sumbitData.activityStartDate = moment(
            this.formData.activityStartDate
          ).format('YYYY-MM-DD')
          io.postPlayload(io.saveOrUpdateActivity, sumbitData, ret => {
            if (ret.success) {
              this.$toast('新建成功')
              this.$router.push({ path: '/main/activity/list' })
            } else {
              this.$alert(ret.desc)
            }
          })
        }
      })
    },
    handleUpload(info) {
      if (info.state === 'SUCCESS') {
        this.formData.bannerUrl = info.url
      }
    },
    loadPeriodData() {
      io.post(
        io.apiAdminPeriodListForAreaTeam,
        {
          areaTeamId: this.formData.areaTeamId
        },
        ret => {
          if (ret.success) {
            this.periods = ret.data
          } else {
            this.$alert(ret.desc)
          }
        }
      )
    },
    addField() {
      this.$refs.win.show({
        width: 800,
        height: 500
      })
    },
    addorDelFieldOption(index) {
      if (index === 0) {
        if (!this.addFieldCount) {
          this.addFieldCount = 0
        }
        this.addFieldCount++
        this.fieldOption.push(this.addFieldCount)
      } else {
        this.fieldOption.splice(index, 1)
      }
    },
    getSource() {
      let action = {}
      io.post(
        io.findFromCategoryList,
        { areaTeamId: this.formData.areaTeamId },
        ret => {
          if (ret.success) {
            ret.data = ret.data || []
            this.categoryList = ret.data.filter(item => {
              if (!item.parentFromCategory) {
                return false
              }
              if (!item.childFromCategories) {
                return false
              }
              return true
            })
            action.resolve()
          } else {
            this.$alert(ret.desc)
          }
        }
      )
      return new Promise((resolve, reject) => {
        action = {
          resolve,
          reject
        }
      })
    },
    resetFieldModal() {
      this.fieldValue = []
      this.fieldTitle = ''
      this.fieldRadio = 0
      this.fieldTips = ''
      this.isNeccess = 1
    },
    saveFieldRadio() {
      let type = this.fieldRadio
      let requireStatus = this.isNeccess
      let title = this.fieldTitle
      if (!title) {
        this.$alert('字段标题不能为空')
        return
      }
      let tips = this.fieldTips
      let objField = [
        {
          msg: [...this.fieldValue],
          requireStatus,
          type,
          title,
          tips
        }
      ]

      this.formData.fields = [...this.formData.fields, ...objField]
      this.resetFieldModal()
      this.$refs.win.close()
    }
  }
}
</script>
<style lang="less" scoped>
.formEdit {
  margin: 30px;
}
.inputBox {
  width: 30%;
}
.addField {
  margin: 30px 0 0 30px;
}
.schoolTeam {
  margin-top: 30px;
}
.fieldInput {
  width: 30%;
}
.fieldInput2 {
  width: 60%;
}
.neccessRow {
  margin-top: 20px;
}
.fieldRight {
  float: right;
}
.fieldRightItem {
  margin-bottom: 15px;
}
.saveFooter {
  display: flex;
  justify-content: center;
}
.fieldItem {
  display: flex;
  margin: 10px 0;
  align-items: center;
}
.fieldShowTitle {
  // width: 50px;
  text-align: right;
  margin-right: 30px;
}
.deleteShowField {
  margin-left: 30px;
}
</style>

